const { app, BrowserWindow, ipcMain } = require('electron/main')
const path = require('node:path')
const { createServer } = require('http-server')
const fs = require('fs')

// 获取exe所在目录下的config路径
const getConfigPath = () => {
  const exePath = path.dirname(app.getPath('exe'))
  return path.join(exePath, 'config')
}

// 读取配置文件
const readConfig = (filename) => {
  try {
    const configPath = path.join(getConfigPath(), filename)
    const data = fs.readFileSync(configPath, 'utf8')
    return JSON.parse(data)
  } catch (error) {
    console.error('读取配置文件失败:', error)
    return null
  }
}

// 创建静态文件服务器
const server = createServer({
  root: path.join(__dirname, 'dist'),
  cache: -1,  // 禁用缓存
  cors: true  // 启用CORS
})

// 启动服务器（使用随机可用端口）
const PORT = 8080
server.listen(PORT)

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        preload: path.join(__dirname, 'preload.js'),
        nodeIntegration: true,
        contextIsolation: true,
        webSecurity: false
      }
  })

  // 通过http-server加载应用
  win.loadURL(`http://localhost:${PORT}/`)

  // 添加IPC处理器来读取配置
  ipcMain.handle('read-config', async (event, filename) => {
    return readConfig(filename)
  })
}

app.whenReady().then(() => {
  ipcMain.handle('ping', () => 'pong')
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  server.close()
  if (process.platform !== 'darwin') {
    app.quit()
  }
})